package com.bbms.util;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.transform.Transformers;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.bbms.entity.Page;

/**
 * @author Administrator
 * Hibernate工具包
 */
public class HibernateUtil {

	private static SessionFactory sessionFactory = buildSessionFactory();
	
	@SuppressWarnings("resource")
	private static SessionFactory buildSessionFactory(){
		// Create the SessionFactory from spring configuration
		// auto closed resourceLoader
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
				
		return (SessionFactory) context.getBean("sessionFactory");
	}
	
	/**
	 * 获得hibernate会话工厂
	 * @return
	 */
	public static SessionFactory getSessionFactory(){
		
		return sessionFactory;
	}
	
	/**
	 * 获得Session
	 * @return
	 */
	public static Session getSession(){
		Session session = sessionFactory.openSession();
		// 开启事务
		if(session.getTransaction().isActive() == false)
			session.beginTransaction();
		
		return session;
	}
	
	/**
	 * 关闭session
	 * @param session
	 */
	public static void closeSession(Session session){
		if(session != null){
			if(session.isOpen()){
				session.close();
			}
		}
	}
	
	/**
	 * 新增实体
	 * @param entity 实体
	 */
	public static void save(Object entity){
		Session session = getSession();
		try{
			
			session.save(entity);
			session.getTransaction().commit();
		} catch (Exception e){
			e.printStackTrace();
			session.getTransaction().rollback();
			throw e;
		} finally{
			closeSession(session);
		}
	}
	
	/**
	 * 更新实体
	 * @param entity 实体
	 */
	public static void update(Object entity){
		Session session = getSession();
		try{
			
			session.update(entity);
			session.getTransaction().commit();
		} catch (Exception e){
			e.printStackTrace();
			session.getTransaction().rollback();
			throw e;
		} finally{
			closeSession(session);
		}
	}
	
	/**
	 * 删除实体
	 * @param entity 实体
	 */
	public static void delete(Object entity){
		Session session = getSession();
		try{
			
			session.delete(entity);
			session.getTransaction().commit();
		} catch (Exception e){
			e.printStackTrace();
			session.getTransaction().rollback();
			throw e;
		} finally{
			closeSession(session);
		}
	}
	
	/**
	 * 分页查询(DetachedCriteria查询)
	 * @param dc 查询结构体
	 * @param currentPage 当前页
	 * @param pageSize 当前页容量
	 * @return 分页数据库
	 */
	public static Page getPage(DetachedCriteria dc, int currentPage, int pageSize){
		Session session = getSession();
		Page page = new Page();
		try {
		    
		    Criteria c = dc.getExecutableCriteria(session);
		    // 获得数据总条目
		    Integer rowCount=Integer.parseInt(c.setProjection(Projections.rowCount()).uniqueResult().toString());
		    c.setProjection(null);
		    c.setFirstResult((currentPage-1)*pageSize);
		    c.setMaxResults(pageSize);
		    List<?> list=c.list();
		    
		    page.setPageNo(currentPage);
		    page.setPageSize(pageSize);
		    page.setRows(list);
		    page.setTotal(rowCount);
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		} finally {
		     closeSession(session);
		}
		
		return page;
	}
	
	/**
	 * 分页查询(普通查询)
	 * @param clazz 实体类类型
	 * @param currentPage 当前页
	 * @param pageSize 当前页容量
	 * @return 结果集数据
	 */
	public static List<?> getList(Class<?> clazz, int currentPage, int pageSize){
		Session session = getSession();
		
		Criteria c = session.createCriteria(clazz);
		c.setFirstResult((currentPage - 1) * pageSize);
		c.setMaxResults(pageSize);
		List<?> list = c.list();
		
		HibernateUtil.closeSession(session);
		
		return list;
	}
	
	/**
	 * sql执行查询操作
	 * @param sql sql语句
	 * @return 执行结果
	 */
	public static List<?> executeSqlQuery(String sql){
		Session session = getSession();
		
		Query query = session.createSQLQuery(sql);
		// 设置结果集的转换方式
		query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
		List<?> list = query.list();
		
		HibernateUtil.closeSession(session);
		
		return list;
	}
	
	/**
	 * sql执行修改、删除操作
	 * @param sql sql语句
	 * @return 执行结果
	 */
	public static int executeSqlUpdate(String sql){
		Session session = getSession();
		
		Query query = session.createSQLQuery(sql);
		int i= query.executeUpdate();
		
		session.getTransaction().commit();
		HibernateUtil.closeSession(session);
		
		return i;
	}
	
	/**
	 * 查询
	 * @param dc 查询条件结构体
	 * @return
	 * @throws Exception
	 */
	public static List<?> query(DetachedCriteria dc){
        Session session = null;
        List<?> list = null;
        try {
            session=getSession();
            Criteria c = dc.getExecutableCriteria(session);
            list = c.list();
            return list;
        }catch (Exception e){
        	e.printStackTrace();
        	throw e;
        }finally {
            closeSession(session);
        }
    }
	
	/** 
	 * 获取表中记录总数
	 * @param dc 查询条件结构体
	 * @return
	 */
	public static int queryTotal(DetachedCriteria dc){
		Session session = null;
		try{
			session = getSession();
			Criteria c = dc.getExecutableCriteria(session);
			Object o=c.setProjection(Projections.rowCount()).uniqueResult();
			return Integer.parseInt(o.toString());
		} finally {
			closeSession(session);
		}
	}
}
